<?php
/**
 * @version		$Id: gendb.php $
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access.
defined('_JEXEC') or die;

jimport('joomla.application.component.modeladmin');

/**
 * Gen Table model.
 *
 * @package		Joomla.Administrator
 * @subpackage	com_gencode
 * @since		1.6
 */
class GenCodeModelGendb extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	1.6
	 */
	protected $text_prefix = 'COM_GEN_CODE_#X#';

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param	object	A record object.
	 * @return	boolean	True if allowed to delete the record. Defaults to the permission set in the component.
	 * @since	1.6
	 */
	protected function canDelete($record)
	{
		if (!empty($record->id)) {
			if ($record->state != -2) {
				return ;
			}
			$user = JFactory::getUser();

			if (!empty($record->catid)) {
				return $user->authorise('core.delete', 'com_gencode.category.'.(int) $record->catid);
			}
			else {
				return parent::canDelete($record);
			}
		}
	}

	/**
	 * Method to test whether a record can have its state changed.
	 *
	 * @param	object	A record object.
	 * @return	boolean	True if allowed to change the state of the record. Defaults to the permission set in the component.
	 * @since	1.6
	 */
	protected function canEditState($record)
	{
		$user = JFactory::getUser();

		// Check against the category.
		if (!empty($record->catid)) {
			return $user->authorise('core.edit.state', 'com_gencode.category.'.(int) $record->catid);
		}
		// Default to component settings if category not known.
		else {
			return parent::canEditState($record);
		}
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'Gendb', $prefix = 'GenCodeTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		Data for the form.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	mixed	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_gencode.gendb', 'gendb', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		// Determine correct permissions to check.
		if ($this->getState('gendb.id')) {
			// Existing record. Can only edit in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.edit');
		} else {
			// New record. Can only create in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.create');
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_gencode.edit.gendb.data', array());

		if (empty($data)) {
			$data = $this->getItem();

			// Prime some default values.
			if ($this->getState('gendb.id') == 0) {
				$app = JFactory::getApplication();
				$data->set('catid', JRequest::getInt('catid', $app->getUserState('com_gencode.banners.filter.category_id')));
			}
		}

		return $data;
	}
	
	function getItem()
	{
		$item = parent::getItem();
		
		$item->fields = $this->getFields($item->id);
		
		return $item;
	}
	
	/**
	 * Function to get fields
	 * @param Int $gendbId
	 * 
	 * @return Object fields
	 */
	function getFields($gendbId)
	{
		$db = JFactory::getDbo();
		
		$query = "SELECT * FROM #__gencode_fields WHERE gendb_id = " . (int) $gendbId . " ORDER BY id ASC";
		$db->setQuery($query);
		
		$result = $db->loadObjectList();
		
		return $result;
	}
	
	/**
	 * Function to save data
	 * @see JModelAdmin::save()
	 */
	function save($data)
	{
		$saveResult = parent::save($data);
		
		$itemId = $this->getState($this->getName().'.id');
		$record = $this->getItem($itemId);
		
		if($saveResult)
		{
			//save field
			$post = JRequest::get('post');
			
			$db = JFactory::getDbo();
			
			$fields = $post['field'];
			
			//delete all fields before insert to db
			$query = "DELETE FROM #__gencode_fields WHERE gendb_id = " . (int) $record->id;
			$db->setQuery($query);
			
			$db->query();
			
			//insert into db
			foreach ($fields['name'] as $key => $field)
			{
				if(!$fields['name'][$key])
					continue;
								
				$isNull = isset($fields['is_null'][$key]) ? $fields['is_null'][$key] : null;
				$autoIncrement = isset($fields['auto_increment'][$key]) ? $fields['auto_increment'][$key] : null;
				
				$query = "INSERT INTO #__gencode_fields SET gendb_id = " . (int) $record->id . ",
															name = '".$fields['name'][$key]."',
															type = '".$fields['type'][$key]."',
															length = '".$fields['length'][$key]."',
															default_type = '".$fields['default_type'][$key]."',
															default_value = '".$fields['default_value'][$key]."',
															collation = '".$fields['collation'][$key]."',
															attributes = '".$fields['attributes'][$key]."',
															is_null = '".$isNull."',
															field_index = '".$fields['field_index'][$key]."',
															auto_increment = '".$autoIncrement."',
															comment = '".$fields['comment'][$key]."',
															created = '".date('Y-m-d H:i:s')."',
															created_by = '".JFactory::getUser()->id."'
									";
				
				$db->setQuery($query);
				$db->query();
				
				if($db->getErrorMsg())
					die($query);
			}
		}
		
		return true;
	}

	/**
	 * Method to stick records.
	 *
	 * @param	array	The ids of the items to publish.
	 * @param	int		The value of the published state
	 *
	 * @return	boolean	True on success.
	 */
	function stick(&$pks, $value = 1)
	{
		// Initialise variables.
		$user	= JFactory::getUser();
		$table	= $this->getTable();
		$pks	= (array) $pks;

		// Access checks.
		foreach ($pks as $i => $pk) {
			if ($table->load($pk)) {
				if (!$this->canEditState($table)) {
					// Prune items that you can't change.
					unset($pks[$i]);
					JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
				}
			}
		}

		// Attempt to change the state of the records.
		if (!$table->stick($pks, $value, $user->get('id'))) {
			$this->setError($table->getError());
			return false;
		}

		return true;
	}

	/**
	 * A protected method to get a set of ordering conditions.
	 *
	 * @param	object	A record object.
	 * @return	array	An array of conditions to add to add to ordering queries.
	 * @since	1.6
	 */
	protected function getReorderConditions($table)
	{
		$condition = array();
		$condition[] = 'catid = '. (int) $table->catid;
		$condition[] = 'state >= 0';
		return $condition;
	}
}
